﻿/* AgileFx Version 2.0
 * An open-source framework for rapid development of applications and services using Microsoft.net
 * Developed by: AgileHead
 * Website: www.agilefx.org
 * This component is licensed under the terms of the Apache 2.0 License.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
using System.Collections.Specialized;

namespace AgileFx.MVC.ViewModels
{
    public class DefaultViewModel
    {
        [NotFormField]
        public string PageTitle { get; set; }

        [NotFormField]
        public string MessageCode { get; set; }

        private List<UIMessage> errors = new List<UIMessage>();

        [NotFormField]
        public List<UIMessage> Errors
        {
            get
            {
                return errors;
            }
        }

        public void AddError(string errorCode)
        {
            Errors.Add(new UIMessage(errorCode));
        }

        public void AddError(string errorCode, params string[] relatedProperty)
        {
            Errors.Add(new UIMessage(errorCode, relatedProperty));
        }

        public void AddErrors(IEnumerable<UIMessage> errors)
        {
            Errors.AddRange(errors);
        }

        public void UpdateFromCollection(NameValueCollection collection)
        {
            var properties = this.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance);

            foreach (var property in properties)
            {
                var attr = property.GetCustomAttributes(typeof(NotFormFieldAttribute), true);
                //should not have NotFormFieldAttribute
                if (attr.Length == 0)
                {
                    if (collection.AllKeys.Contains(property.Name))
                        property.SetValue(this, collection[property.Name], null);
                }
            }
        }
    }
}
